package com.owc.common.custom.module;

import com.owc.common.tool.CryptographUtils;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.JsonSerializer;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializerProvider;

import java.io.IOException;
import java.io.StringWriter;

/**
 * @Author xiaom
 * @Date 2019/12/3 10:15
 * @Version 1.0.0
 * @Description <>
 **/
public class EncryptedJsonSerializer extends JsonSerializer<Object> {

    private final JsonSerializer<Object> serializer;

    public EncryptedJsonSerializer(JsonSerializer<Object> serializer) {
        this.serializer = serializer;
    }


    @Override
    public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        StringWriter stringWriter = new StringWriter();
        ObjectCodec objectCodec = jsonGenerator.getCodec();
        JsonGenerator nestedGenerator = null;
        if(o == null || String.valueOf(o).equals("")){
            if (serializer == null) {
                serializerProvider.defaultSerializeValue(o, jsonGenerator);
            }else{
                serializer.serialize(o, jsonGenerator, serializerProvider);
            }
            return;
        }
        if(objectCodec instanceof ObjectMapper){
            nestedGenerator = (((ObjectMapper) objectCodec).getJsonFactory().createJsonGenerator(stringWriter));
        }

        if (nestedGenerator == null) {
            throw new NullPointerException("nestedGenerator == null");
        }
        if (serializer == null) {
            serializerProvider.defaultSerializeValue(o, nestedGenerator);
        }else{
            serializer.serialize(o, nestedGenerator, serializerProvider);
        }
        nestedGenerator.close();
        String value = stringWriter.getBuffer().toString();
        try {
            jsonGenerator.writeString(CryptographUtils.MD5(value));
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
}
